package com.warm.kafkalearn.service.impl;

import com.warm.kafkalearn.dao.UserMapper;
import com.warm.kafkalearn.pojo.User;
import com.warm.kafkalearn.service.UserService;
import joptsimple.internal.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    StringRedisTemplate template;

    static final String KEY_USER_INFO__NAME = "com_demo_user_info_007_%s";

    public List<User> getUser(int age) {
        return userMapper.getUser(age);
    }

    @Override
    @Cacheable(value = "user_details",key = "#uid",unless = "#result == null ")
    public User getUserDetailByUid(int uid) {
        System.out.println("Cacheable  有请求过来了！");
        User user = userMapper.getUserDetailByUid(uid);
        return user;
    }

    @Override
    public String getUserNameById(int uid) {
        String userName = "未知用户";
        try {
            userName = template.opsForValue().get(String.format(KEY_USER_INFO__NAME, uid));
            if (Strings.isNullOrEmpty(userName)) {
                // Redis中没有就读数据库
                User userDetails = getUserDetailByUid(uid);
                if (userDetails != null && !Strings.isNullOrEmpty(userDetails.getEmail())) {
                    userName = userDetails.getEmail();
                }
            }
        }catch(Exception e){
            System.out.println(e.toString());
        }

        return userName;
    }

    @Override
    public void setUserNameById(Integer uid, String userName) {
        template.opsForValue().set(String.format(KEY_USER_INFO__NAME, uid), userName);
    }

    @Override
    @CachePut(value = "user_details",key = "#user.id")
    public User updateUserInfo(User user) {
        System.out.println("CachePut 有请求过来了！");
        if(userMapper.updateByPrimaryKeySelective(user) > 0){
            User userDetail = userMapper.getUserDetailByUid(user.getId());
            return userDetail;
        }
        return null;
    }

    @Override
    @CacheEvict(value = "user_details", key = "#uid")
    public int deleteUserInfoById(int uid) {
        System.out.println(" CacheEvict 有请求过来了");
        return userMapper.deleteByPrimaryKey(uid);
    }
}
